package oracle.apps.financials.collection.adapter;

import org.achartengine.GraphicalView;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import android.animation.AnimatorSet;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;

public class XYChartTimeRangeAnimator {

	private GraphicalView mView;

	private XYMultipleSeriesRenderer mRenderer;
	
	public static int  DURATION_TIME=1000;

	private TypeEvaluator<Double> mDoubleTypeEvaluator = new TypeEvaluator<Double>() {
		@Override
		public Double evaluate(float fraction, Double startValue, Double endValue) {
			return (fraction * (endValue - startValue) + startValue);
		}

	};

	private AnimatorUpdateListener animStartUpdateListener = new AnimatorUpdateListener() {

		@Override
		public void onAnimationUpdate(ValueAnimator animation) {

			mRenderer.setXAxisMin((Double) animation.getAnimatedValue());
			if (mRenderer.getScalesCount() > 1) {
				mRenderer.setXAxisMin((Double) animation.getAnimatedValue(), 1);
			}

		}
	};

	private AnimatorUpdateListener animEndUpdateListener = new AnimatorUpdateListener() {
		
		@Override
		public void onAnimationUpdate(ValueAnimator animation) {
			mRenderer.setXAxisMax((Double) animation.getAnimatedValue());
			if (mRenderer.getScalesCount() > 1) {
				mRenderer.setXAxisMax((Double) animation.getAnimatedValue(), 1);
			}		
			mView.postInvalidate();
			
		}
	};

	public XYChartTimeRangeAnimator() {
		super();
	}

	public void start(GraphicalView mView, double start, double end) {
		this.mView = mView;
		this.mRenderer = (XYMultipleSeriesRenderer) this.mView.getRenderer();
		
		AnimatorSet animSet = new AnimatorSet();
		ValueAnimator vAnimStart = ValueAnimator.ofObject(mDoubleTypeEvaluator, mRenderer.getXAxisMin(), start);
		ValueAnimator vAnimEnd = ValueAnimator.ofObject(mDoubleTypeEvaluator, mRenderer.getXAxisMax(), end);
		vAnimStart.addUpdateListener(animStartUpdateListener);
		vAnimEnd.addUpdateListener(animEndUpdateListener);
		vAnimStart.setDuration(DURATION_TIME);
		vAnimEnd.setDuration(DURATION_TIME);

		animSet.playTogether(vAnimStart, vAnimEnd);
		animSet.start();
	}

}
